/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-04-14 20:04:40
 * @LastEditTime: 2022-05-13 20:06:37
 * @LastEditors: Junhuang
 * @Reference:
 */
'use strict';

const Controller = require('egg').Controller;

// 参数校验规则
const rules = {
  key: { type: 'string', required: true, desc: '角色标识' },
  description: { type: 'string', required: false, desc: '描述' },
  array_routes: { type: 'string', required: true, desc: '描述' },
};

class RoleController extends Controller {
  async list() {
    const { ctx, app } = this;
    const where = {};

    // 组织查询条件
    // id用全等
    if (ctx.query.id && ctx.query.id.length > 0) {
      where.id = ctx.query.id;
    }
    // stauts全等
    if (ctx.query.status) {
      where.status = parseInt(ctx.query.status);
    }
    // name用like
    const Op = app.Sequelize.Op;
    if (ctx.query.key && ctx.query.key.length > 0) {
      where.key = {
        [Op.like]: '%' + ctx.query.key + '%',
      };
    }
    // console.log('where=', where);

    const options = {};
    // 组织排序
    if (ctx.query.sort && ctx.query.sort.length > 0) {
      const direction = ctx.query.sort.slice(0, 1) === '+' ? 'ASC' : 'DESC';
      const sortColumn = ctx.query.sort.slice(1);
      options.order = [[ sortColumn, direction ]];
    }
    // console.log('options=', options);

    const res = await ctx.pageAndCount(app.model.Role, where, options);
    const items = [];
    if (res && res.count && res.count > 0) {
      res.rows.forEach(el => {
        if (el.array_routes && el.array_routes.length > 0) {
          const temp = el.array_routes.split(',');
          const arr = [];
          temp.forEach(item => {
            arr.push({ path: item });
          });
          el.array_routes = arr;
        }
        const role = JSON.parse(JSON.stringify(el));
        items.push(role);
      });
    }
    ctx.apiSuccesss({
      total: res.count,
      items,
    });
  }

  // 获取特定角色下的用户，分页
  async getAdminsByRole() {
    const { ctx, app } = this;
    const where = {};
    const Op = app.Sequelize.Op;
    // id为角色id
    const { id } = ctx.params;
    // 组织查询条件
    const { no, name, department_name } = ctx.query;

    // no用全等
    if (no && no.length > 0) {
      where.no = no;
    }

    const dept_where = {};
    // 【特别注意】department_name 是子表中的
    if (department_name && department_name.length > 0) {
      dept_where.name = {
        [Op.like]: '%' + department_name + '%',
      };
    }

    // name用like
    if (name && name.length > 0) {
      where.name = {
        [Op.like]: '%' + name + '%',
      };
    }

    const options = {
      include: [{
        model: app.model.Department,
        as: 'department',
        attributes: [[ 'name', 'department_name' ], 'id_path', 'name_path' ],
        where: dept_where,
        order: [[ 'id_path', 'asc' ]],
      }, {
        model: app.model.Role,
        as: 'myroles',
        where: {
          id: parseInt(id),
        },
      }],
    };

    const res = await ctx.pageAndCount(app.model.Admin, where, options);
    const items = [];
    if (res && res.count && res.count > 0) {
      res.rows.forEach(el => {
        const admin = JSON.parse(JSON.stringify(el));
        admin.department_name = admin.department.department_name;
        delete admin.department;
        delete admin.myroles;
        items.push(admin);
      });

      await Promise.all(
        res.rows.map(async el => {
          const myroles = await el.getMyroles();
          const strRoles = await this.getRolesStr(myroles);
          const temp = items.find(item => {
            return item.id === el.id;
          });
          if (temp) {
            temp.rids = strRoles.ids;
            temp.rkeys = strRoles.keys;
          }
        })
      );
    }
    ctx.apiSuccesss({
      total: res.count,
      items,
    });
  }

  // 修改角色
  async update() {
    const { ctx, app } = this;
    const {
      key,
      array_routes,
      description,
    } = ctx.request.body;

    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: '角色id',
      },
      ...rules,
    });


    const role = await app.model.Role.findOne({
      where: {
        id: ctx.params.id,
      },
    });

    if (!role) {
      return ctx.throw(404, '该记录不存在');
    }

    const res = await role.update({
      key,
      array_routes,
      description,
    });

    return ctx.apiSuccesss(res);
  }

  // 新增角色
  async save() {
    const { ctx, app } = this;
    const {
      key,
      array_routes,
      description,
    } = ctx.request.body;

    ctx.validate({
      ...rules,
    });

    const role = await app.model.Role.create({
      key,
      array_routes,
      description,
    });

    return ctx.apiSuccesss(role);
  }

  // 获取角色基本信息
  // 路由：/role/:id
  async get() {
    const { ctx, app } = this;
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: '角色id',
      },
    });
    const { id } = ctx.params;
    const role = await app.model.Role.findByPk(id);
    if (!role) {
      return ctx.apiFail('无此角色');
    }
    return ctx.apiSuccesss(role);
  }

  // 删除
  async destroy() {
    const { ctx, app } = this;
    const { id } = ctx.params;
    ctx.validate({
      id: {
        type: 'int', required: true, desc: '角色id',
      },
    });
    const role = await app.model.Role.findOne({
      where: {
        id,
      },
    });

    if (!role) {
      return ctx.throw('角色不存在！');
    }

    const res = await role.destroy();
    ctx.apiSuccesss(`成功删除{id:${res.id},name:${res.name}}的角色`);
  }

  // 将管理员设置为可用状态，包括将草稿状态=》可用状态 及 禁用状态=》可用状态
  async enable() {
    const { ctx, app } = this;
    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: '角色id',
      },
    });

    const role = await app.model.Role.findOne({
      where: {
        id: ctx.params.id,
      },
    });

    if (!role) {
      return ctx.throw(404, '该角色不存在');
    }

    if (role.status === 1) {
      return ctx.throw('该角色已经为正常状态，不需要此操作！');
    }

    let res = await role.update({
      status: 1,
    });

    res = JSON.parse(JSON.stringify(res));

    return ctx.apiSuccesss(res);
  }

  // 将管理员设置为可用状态，包括将草稿状态=》可用状态 及 禁用状态=》可用状态
  async disable() {
    const { ctx, app } = this;
    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: '角色id',
      },
    });

    const role = await app.model.Role.findOne({
      where: {
        id: ctx.params.id,
      },
    });

    if (!role) {
      return ctx.throw(404, '该管理员不存在');
    }

    if (role.status !== 1) {
      return ctx.throw('非正常状态角色无法禁用！');
    }

    let res = await role.update({
      status: -1,
    });

    res = JSON.parse(JSON.stringify(res));

    return ctx.apiSuccesss(res);
  }

  async myRoles() {
    const { ctx } = this;
    const res = await ctx.authAdmin.getMyroles();
    return ctx.apiSuccesss(res);
  }

  // 判断key不重复
  async isRightKey() {
    const { ctx, app } = this;
    const key = ctx.query.key;
    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: '角色id',
      },
      key: {
        type: 'string',
        required: true,
        desc: '角色key',
      },
    });
    const Op = app.Sequelize.Op;
    const role = await app.model.Role.findOne({
      where: {
        key,
        id: {
          [Op.ne]: ctx.params.id,
        },
      },
    });

    if (role) {
      return ctx.apiFail('此角色key不合法！');
    }
    return ctx.apiSuccesss('此角色key合法！');

  }

  // 测试role与admin的关系
  async testRoleAdmin() {
    const { app, ctx } = this;
    const role = await app.model.Role.findOne({
      include: [{
        model: app.model.Admin,
        as: 'admins',
      }],
      where: {
        id: 1,
      },
    });
    ctx.apiSuccesss(role);
  }
}

module.exports = RoleController;
